package com.woniu.service.impl;

import com.woniu.entity.Order;
import com.woniu.entity.OrderItem;
import com.woniu.entity.UserCart;
import com.woniu.entity.dto.OrderParamDTO;
import com.woniu.mapper.OrderMapper;
import com.woniu.producer.DelayProducer;
import com.woniu.service.OrderService;
import com.woniu.util.ResponseData;
import com.woniu.util.SnowflakeIdGenerator;
import com.woniu.util.UserContext;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

@Service
@AllArgsConstructor
public class OrderServiceImpl implements OrderService {

    private OrderMapper orderMapper;

    private DelayProducer delayProducer;
    /**
     * 用户下单接口
     * 1:判断商品的库存是否足够
     * 2:写入订单表和订单详情表
     * 3:修改库存
     * 4:购物车状态
     * 5:用户15分钟内没有付款取消订单
     * @return
     */
    @Override
    public ResponseData<?> addOrder(OrderParamDTO orderParamDTO) throws InterruptedException, ParseException {
        //1:判断商品的库存是否足够
        List<UserCart> userCarts = orderMapper.queryBookAndStoreCount(orderParamDTO.getCartIds());

        List<String> bookCountLack = userCarts.stream()
                .filter(e -> e.getStoreCount() < e.getBuyNum())
                .map(e -> e.getName())
                .collect(Collectors.toList());

        //专门放库存不足的书籍名称
//        List<String> bookCountLack = new ArrayList<>();
//        for (UserCart userCart : userCarts) {
//            if (userCart.getStoreCount() < userCart.getBuyNum()){
//                //证明库存不足
//                bookCountLack.add(userCart.getName());
//            }
//        }

        if (!CollectionUtils.isEmpty(bookCountLack)){
            return ResponseData.ok(bookCountLack);
        }

        //2写入订单表和订单详情表
        Order order = new Order();
        Integer userId = UserContext.getUserId();
        order.setUserId(userId);
        order.setAddressId(orderParamDTO.getAddrId());

        BigDecimal totalPrice = BigDecimal.ZERO;

        for (UserCart userCart : userCarts) {
            totalPrice.add(userCart.getTotalPrice());
        }
        order.setTotalPrice(totalPrice); //订单总价格

        SnowflakeIdGenerator sfg = new SnowflakeIdGenerator();
        String orderNum = String.valueOf(sfg.nextId());

        order.setOrderNum(orderNum); //主键
        orderMapper.addOrder(order);

        //批量写入订单详情表
        List<OrderItem> orderItems = new ArrayList<>();
        for (UserCart userCart : userCarts) {
            OrderItem orderItem = new OrderItem();
            orderItem.setBuyCount(userCart.getBuyNum());
            orderItem.setPrice(userCart.getBuyPrice());
            orderItem.setOrderId(orderNum);
            orderItem.setSumPrice(userCart.getTotalPrice());
            orderItem.setBookName(userCart.getName());
            orderItem.setBookId(userCart.getBookId());

            orderItems.add(orderItem);
        }
        orderMapper.batchAddOrderItem(orderItems);

        //3:修改库存
        orderMapper.batchBookCount(userCarts);

        //4:修改购物车状态
        orderMapper.batchUserCartStatus(orderParamDTO.getCartIds());

        //5:发送一个延迟15分钟的延迟队列（用户没有付款取消订单）
        Integer ttl = 15*60*1000;
        delayProducer.send("delay",orderNum,1000);
        return ResponseData.ok();
    }
}
